/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.modules.sys.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.persistence.Page;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.modules.sys.entity.Company;
import cn.net.ecode.modules.sys.entity.Employee;
import cn.net.ecode.modules.sys.entity.Office;
import cn.net.ecode.modules.sys.entity.Post;
import cn.net.ecode.modules.sys.entity.Role;
import cn.net.ecode.modules.sys.entity.User;
import cn.net.ecode.modules.sys.service.CompanyService;
import cn.net.ecode.modules.sys.service.EmpUserService;
import cn.net.ecode.modules.sys.service.EmployeeService;
import cn.net.ecode.modules.sys.service.OfficeService;
import cn.net.ecode.modules.sys.service.PostService;
import cn.net.ecode.modules.sys.service.RoleService;
import cn.net.ecode.modules.sys.service.UserService;
import cn.net.ecode.modules.sys.utils.UserUtils;

/**
 * 员工用户Controller
 * @author ThinkGem
 * @version 2015-4-24
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/empUser")
public class EmpUserController extends BaseController {

	@Autowired
	private EmpUserService empUserService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private PostService postService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private OfficeService officeService;

	@ModelAttribute
	public Employee get(String userCode, boolean isNewRecord) {
		return empUserService.getByUserCode(userCode, isNewRecord);
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = {"index"})
	public String index(User user, Model model) {
		return "modules/sys/empUserIndex";
	}
	
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = {"list", ""})
	public String list(Employee employee, Model model) {
		// 获取岗位列表
		Post post = new Post();
		post.setStatus(Post.STATUS_NORMAL);
		model.addAttribute("allPosts", postService.findList(post));
		return "modules/sys/empUserList";
	}

	@RequiresUser
	@ResponseBody
	@RequestMapping(value = "listData")
	public Page<Employee> listData(Employee employee, HttpServletRequest request, HttpServletResponse response) {
		Page<Employee> page = null;
		User user = employee.getLoginInfo();
		user.setMgrType(User.MGR_TYPE_NOT_ADMIN); // 非管理员
		page = empUserService.findPage(new Page<Employee>(request, response), employee);
		return page;
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "form")
	public String form(Employee employee, HttpServletRequest request, Model model) {
		
		// 设置默认的公司
		if (employee.getCompany() == null || employee.getCompany().getId() == null) {
			if (UserUtils.getUser().getEmployee() != null) {
				employee.setCompany(UserUtils.getUser().getEmployee().getCompany());
			}
		}
		
		// 设置默认的部门
		if (employee.getOffice() == null || employee.getOffice().getId() == null) {
			if (UserUtils.getUser().getEmployee() != null) {
				employee.setOffice(UserUtils.getUser().getEmployee().getOffice());
			}
		}
		
		// 获取当前操作
		String op = request.getParameter("op");

		// 获取当前编辑用户的角色和权限
		if ("authorize".equals(op)) {
			User user = employee.getLoginInfo();
			user.setRoleList(userService.findUserRoleList(user));
			user.setUserDataScopeList(userService.findUserDataScopeList(user));
		}
		
		// 新增用户时，设置默认选择的角色
		if(employee.getIsNewRecord()){
			String roleCodes = Global.getConfig("sys.user.defaultSetRoleCodes");
			if (roleCodes != null){
				employee.getLoginInfo().setRoleCodes(roleCodes);
			}
		}
		
		// 获取可分配的权限
		model.addAttribute("allRoles", roleService.findList(new Role()));
		model.addAttribute("allCompanys", companyService.findList(new Company()));
		model.addAttribute("allOffices", officeService.findList(new Office()));
		
		// 获取当前编辑用户的岗位
		employee.setPostList(postService.getPostByEmployee(employee));
		
		// 获取岗位列表
		Post post = new Post();
		post.setStatus(Post.STATUS_NORMAL);
		model.addAttribute("allPosts", postService.findList(post));
		
		model.addAttribute("employee", employee);
		return "modules/sys/empUserForm";
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(Employee employee, HttpServletRequest request) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		if (User.isAdmin(employee.getLoginInfo().getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		StringBuilder message = new StringBuilder();
		if (!beanValidator(message, employee)) {
			return renderResult(Global.FALSE, message);
		}
		if (!beanValidator(message, employee.getLoginInfo())) {
			return renderResult(Global.FALSE, message);
		}
		
		// 获取当前操作
		String op = request.getParameter("op");
		
		// 用户授权操作
		if ("authorize".equals(op)) {
			userService.saveAuthorize(employee.getLoginInfo());
		}
		// 保存用户操作
		else {

			employee.setEmpCode(employee.getLoginInfo().getLoginCode());
			employee.setEmpName(employee.getLoginInfo().getUserName());
			employee.setOfficeCode(employee.getOffice().getId());
			empUserService.save(employee);
		}
		return renderResult(Global.TRUE, "保存用户'" + employee.getEmpName() + "'成功");
	}

	/**
	 * 停用用户
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:disable")
	@RequestMapping(value = "disable")
	public String disable(Employee employee) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		String message = "";
		if (UserUtils.getUser().getUserCode().equals(employee.getLoginInfo().getUserCode())) {
			message = "停用用户失败, 不允许停用当前用户";
		} else {
			empUserService.disableUser(employee);
			message = "停用用户成功";
		}
		return renderResult(Global.TRUE, message);
	}

	/**
	 * 启用用户
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:activate")
	@RequestMapping(value = "activate")
	public String enable(Employee employee) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		empUserService.activateUser(employee);
		return renderResult(Global.TRUE, "启用用户成功");
	}

	/**
	 * 删除用户
	 * @param employee
	 * @return
	 */
	@RequiresPermissions("sys:user:delete")
	@ResponseBody
	@RequestMapping(value = "delete")
	public String delete(Employee employee) {
		employee.setEmpCode(employee.getUserCode());
		empUserService.delete(employee);
		return renderResult(Global.TRUE, "删除用户'" + employee.getEmpName() + "'成功！");
	}

	/**
	 * 验证编码是否有效
	 * @param oldEmpCode
	 * @param empCode
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "checkEmpCode")
	public String checkEmpCode(String oldEmpCode, String empCode) {
		if (empCode != null && empCode.equals(oldEmpCode)) {
			return "true";
		} else if (empCode != null && employeeService.get(empCode) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 验证工号是否有效
	 * @param oldEmpNo
	 * @param empNo
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "checkEmpNo")
	public String checkEmpNo(String oldEmpNo, String empNo) {
		if (empNo != null && empNo.equals(oldEmpNo)) {
			return "true";
		} else if (empNo != null && employeeService.getByEmpNo(empNo) == null) {
			return "true";
		}
		return "false";
	}
}
